package action;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import org.apache.struts2.ServletActionContext;
import org.springframework.web.multipart.MultipartFile;
import utils.ResultUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

/**
 * @author Lei
 * @create 2021-04-16 19:44
 */
public class FileAction {
    private File image;

    private String imageFileName;
    private String imageFileContentType;


    public String getImageFileName() {
        return imageFileName;
    }

    public void setImageFileName(String imageFileName) {
        this.imageFileName = imageFileName;
    }

    public String getImageFileContentType() {
        return imageFileContentType;
    }

    public void setImageFileContentType(String imageFileContentType) {
        this.imageFileContentType = imageFileContentType;
    }

    public File getImage() {
        return image;
    }

    public void setImage(File image) {
        this.image = image;
    }

    public String uploadImg() throws Exception {
        //原来的名称
        String newFilename = DateUtil.format(new Date(), "yyyyMMddHHssmm");
        newFilename += "." + "jpg";

        //在这个地方跟换成为需要的本地的一个上传的文件的目录，然后进行之后的修改，这样也好进行之后的修改，
        //当时直接写的时候，需要重新启动服务器才可以继续之后的访问，之后就需要设置成为直接在tomcat下面的设置的一个方法。
        String realpath =ServletActionContext.getServletContext().getRealPath("upload");
        //文件保存的物理路径
        String filePath = realpath + File.separator + newFilename;
        //需要保存的网络路径
        String url = "upload" + "/" + newFilename;
        try {
            File saveFile = new File(filePath);
            FileUtil.copy(image, saveFile,true);
            HashMap<String, Object> stringObjectHashMap = new HashMap<>();
            stringObjectHashMap.put("code", 200);
            stringObjectHashMap.put("msg", "上传成功");
            stringObjectHashMap.put("data", url);
            ResultUtils.toJson(ServletActionContext.getResponse(), stringObjectHashMap);
            return "success";
        } catch (IOException e) {
            e.printStackTrace();
        }

        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("code", 0);
        stringObjectHashMap.put("msg", "上传失败");
        ResultUtils.toJson(ServletActionContext.getResponse(), stringObjectHashMap);
        return "fail";
    }
}
